package org.sport.logic;

import org.sport.dbInterface.*;
import org.sport.init.SportClientSymbol;
import org.sport.init.SportServerSymbol;
import org.sport.model.entityModel.*;
import org.sport.model.jsonModel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by zehong
 *
 * 处理联系人界面的逻辑，包括展示我的联系人，我的群组及创建群组，新朋友的请求及处理，搜索添加新朋友？搜索添加新群组？
 */

@Service
public class Logic_LinkPeople {


    @Autowired
    LinManOperation linkOperation;

    @Autowired
    LogicUtils logicUtils;


//    @Autowired
//    LogicUtils logicUtils2;

    @Autowired
    HisInfoOperation hisInfoOperation;

    @Autowired
    LinAppHisOperation linkAppHisOperation;

    @Autowired
    GroupOperation groupOperation;

    @Autowired
    GroLinkUserOperation groLinkUserOperation;



    //主界面，一进去就要展示我的联系人列表，以及未读消息数量
    public ArrayList<Json_4_home> home(Json_4_home json_4_home)
    {
        System.out.println("进入Logic-Link-home");

        ArrayList<Json_4_home> resultList=new ArrayList<>();

        /**
         * 找用户
         * 找所有联系人，提取信息
         * 找历史聊天记录表，把未读的数量找出
         */


        //手机用户主人
        UsertableEntity user=logicUtils.findUser(json_4_home.getPhoneNumber());
        //根据该用户在联系人表中找到所有他的联系人
        List<UsertableEntity> userAlllink=linkOperation.findUserLinkMan(user);
        //找到该用户未读信息数量
        List<HistoryinfotableEntity> userAllMsg=hisInfoOperation.findAllHisInfoByWho(user);
        int unReadMsg=0;
        for (int i = 0; i < userAllMsg.size(); i++) {

            System.out.println("进入userAllMsg");

            if (userAllMsg.get(i).getStatus().equals(SportServerSymbol.historyinfotable.STATUS_UNREAD)){
                unReadMsg++;
            }
        }
        //填充数据
        for (int j = 0; j < userAlllink.size(); j++) {

            System.out.println("进入userAlllink");

            Json_4_home temp=new Json_4_home();
            temp.setLinkPhoneNumber(userAlllink.get(j).getPhoneNumber());
            temp.setLinkIcon(userAlllink.get(j).getHeadIcon());
            temp.setLinkNickname(userAlllink.get(j).getName());
            temp.setUnReadMsg(unReadMsg);
            temp.setResult(SportClientSymbol.LinkPeople.HOME_RESULT_SUCCESS);

            resultList.add(temp);
        }

        return resultList;
    }






    //新的朋友，进入新的朋友请求的页面,在这里可以看到其他人的请求信息
    public ArrayList<Json_4_newFriend_list> newFriend_list(Json_4_newFriend_list json_4_newFriend_list)
    {
        System.out.println("进入Logic-Link-newFriend_list");

        ArrayList<Json_4_newFriend_list> resultList=new ArrayList<>();


        /**
         * 找用户
         * 找linkapplyhistory表，找到别人申请信息
         * 填充信息返回
         */


        //手机用户主人
        UsertableEntity user=logicUtils.findUser(json_4_newFriend_list.getPhoneNumber());
        List<LinkapplyhistoryEntity> userAllBeApply= linkAppHisOperation.findByBeApplyUserId(user);
        //填充数据
        for (int i = 0; i < userAllBeApply.size(); i++) {

            //筛选出未处理的请求
            if (userAllBeApply.get(i).getStatus().equals(SportServerSymbol.linkapplyhistory.STATUS_UNHANDLE)){
                Json_4_newFriend_list temp=new Json_4_newFriend_list();
                UsertableEntity temp2=userAllBeApply.get(i).getUsertableByApplyUserId();
                temp.setLinkPhoneNumber(temp2.getPhoneNumber());
                temp.setLinkIcon(temp2.getHeadIcon());
                temp.setLinkNickname(temp2.getName());
                temp.setLinkBrief(temp2.getBrief());
                temp.setResult(SportClientSymbol.LinkPeople.NEWFRIENDLIST_RESULT_SUCCESS);

                resultList.add(temp);
            }
        }



        return resultList;
    }




    //新的朋友，进入新的朋友请求的页面,可以处理请求信息，接收或者拒绝他人的请求
    public Json_4_newFriend_handle newFriend_handle(Json_4_newFriend_handle json_4_newFriend_handle)
    {
        System.out.println("进入Logic-Link-newFriend_handle");


        /**
         * 找用户
         * 接受则两个人的联系表都要加，同时申请记录表状态置为接受
         * 拒绝则只是申请记录表状态置为拒绝
         */


        //手机用户主人及操作的陌生人申请者
        UsertableEntity userBeApply=logicUtils.findUser(json_4_newFriend_handle.getPhoneNumber());
        UsertableEntity userApply=logicUtils.findUser(json_4_newFriend_handle.getLinkPhoneNumber());

        //找到对方申请我为好友的记录数据
        LinkapplyhistoryEntity userBeApplyAllList= linkAppHisOperation.findOneBy2User(userApply,userBeApply);

        //接受该好友请求
        if (json_4_newFriend_handle.getAcceptOrNot()==SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_ACCEPTORNOT_ACCRPT){

            System.out.println("接受好友请求");

            //往联系人表中添加时，需要保证原来没有这两个人的好友关系数据，保证唯一性
            if (linkOperation.findOneLinkMan(userBeApply,userApply)==null){

                //联系人的表要加两个人互为好友的两条信息
                if (linkOperation.addOneLinkMan(userBeApply,userApply)){
                    System.out.println("我已添加对方为好友");
                    if (linkOperation.addOneLinkMan(userApply,userBeApply)){
                        System.out.println("对方已添加我为好友");
                        //同时申请记录表状态置为接受
                        linkAppHisOperation.updateUserStatus(userApply,userBeApply,SportServerSymbol.linkapplyhistory.STATUS_ACCEPT);
                        json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_RESULT_ACCEPT_SUCCESS);
                    }else {
                        System.out.println("对方添加我为好友操作失败");
                        json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_RESULT_ACCEPT_FAIL_OTHER);
                    }
                }else {
                    System.out.println("我添加对方为好友操作失败");
                    json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_RESULT_ACCEPT_FAIL_ME);
                }

            }else {
                System.out.println("你和他已经是好友了！");
                json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_RESULT_ACCEPT_FAIL_ALREADY);
            }

        }else if (json_4_newFriend_handle.getAcceptOrNot()==SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_ACCEPTORNOT_REFUSE){
            //拒绝则只需要把申请表置为refuse
            System.out.println("拒绝好友请求");
            linkAppHisOperation.updateUserStatus(userApply,userBeApply,SportServerSymbol.linkapplyhistory.STATUS_REFUSE);
            json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDLIST_RESULT_SUCCESS);

        }else {
            System.out.println("未知请求指令");
            json_4_newFriend_handle.setResult(SportClientSymbol.LinkPeople.NEWFRIENDHANDLE_RESULT_UNKNOW);
        }

        return json_4_newFriend_handle;
    }




    //群组，进入群组页面，可以看到有关于我的所有群组
    public  ArrayList<Json_4_group> group(Json_4_group json_4_group)
    {
        System.out.println("进入Logic-Link-group");

        ArrayList<Json_4_group> resultList=new ArrayList<>();

        /**
         * 找用户
         * 找groupTable，看ownid的对应的群组
         * 填充数据返回
         */

        //找到我拥有的所有的群组
        List<GrouptableEntity> myAllGroups=groupOperation.findByOwnerId(logicUtils.findUser(json_4_group.getPhoneNumber()));

        //填充数据
        for (int i = 0; i < myAllGroups.size(); i++) {

            System.out.println("查找group");

            Json_4_group temp=new Json_4_group();
            GrouptableEntity temp2=myAllGroups.get(i);
            temp.setGroupId(temp2.getId());
            temp.setGroupIcon(temp2.getIcon());
            temp.setGroupName(temp2.getTitle());
            temp.setGroupIntroduce(temp2.getTheam());
            temp.setLocation(temp2.getLocation());
            temp.setResult(SportClientSymbol.LinkPeople.GROUP_RESULT_SUCCESS);

            resultList.add(temp);

        }

        return resultList;
    }




    //点击新增群组按钮，添加新的群组
    public Json_4_creategroup creategroup(Json_4_creategroup json_4_creategroup)
    {
        System.out.println("进入Logic-Link-creategroup");


        /**
         * 找用户
         * 新增一个group
         * 同时还要在群组人员列表加上我在这个群组中！
         * 填充数据返回
         */

        //新增一个group，填充数据
        GrouptableEntity newGroup=new GrouptableEntity();
        newGroup.setCreateTime(new Timestamp(System.currentTimeMillis()));
        newGroup.setTheam(json_4_creategroup.getGroupIntroduce());
        newGroup.setTitle(json_4_creategroup.getGroupName());
        newGroup.setLocation(json_4_creategroup.getLocation());
        newGroup.setUsertableByOwnerId(logicUtils.findUser(json_4_creategroup.getPhoneNumber()));

        //给群组头像起个名字
        String iconName=json_4_creategroup.getPhoneNumber()+"_"+new Date().getTime()+".jpg";
        //获取群组头像，并保存到服务器图片地址中
        boolean getImageResult=false;
        boolean getImageResult2=false;
        try{
            //getImageResult= JsonImageString.generateImage(json_4_creategroup.getGroupIconString(), SportServerSymbol.tomcatImgPath+"\\"+iconName);
            //getImageResult2= JsonImageString.generateImage(json_4_creategroup.getGroupIconString(), SportServerSymbol.ImgStoragePath+"\\"+iconName);
            getImageResult= JsonImageString.generateImage(json_4_creategroup.getGroupIconString(), SportServerSymbol.tomcatImgPath+"/"+iconName);
            getImageResult2= JsonImageString.generateImage(json_4_creategroup.getGroupIconString(), SportServerSymbol.ImgStoragePath+"/"+iconName);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(getImageResult&&getImageResult2){
            //获取活动图片成功
            String iconPath="/0/upload_img/"+iconName;
            System.out.println("图片在服务器地址为"+iconPath);

            json_4_creategroup.setGroupIconURL(iconPath);
            newGroup.setIcon(iconPath);

            //往聊天群组中添加一条记录
            boolean addResult=groupOperation.addOneGroup(newGroup);
            if (addResult){
                //新增群组成功
                System.out.println("新增群组成功");
                json_4_creategroup.setResult(SportClientSymbol.LinkPeople.CREATEGROUP_RESULT_SUCCESS);
            }else {
                //新增群组失败
                System.out.println("新增群组失败");
                json_4_creategroup.setResult(SportClientSymbol.LinkPeople.CREATEGROUP_RESULT_FAIL);
            }
        }else{
            //获取群组头像失败
            System.out.println("获取群组头像失败");
            json_4_creategroup.setResult(SportClientSymbol.LinkPeople.CREATEGROUP_RESULT_FAIL_IMAGEERROR);
        }



        //还要在群组人员列表加上我在这个群组中！（此处默认最新添加的群组就是我刚刚添加的群组）
        List<GrouptableEntity> allGroup=groupOperation.findAllG();
        GrouplinkuserEntity myNewGrouplink=new GrouplinkuserEntity();
        myNewGrouplink.setGrouptableByGroupId(allGroup.get(allGroup.size()-1));
        myNewGrouplink.setUsertableByUserId(logicUtils.findUser(json_4_creategroup.getPhoneNumber()));
        groLinkUserOperation.addOneData(myNewGrouplink);

        return json_4_creategroup;
    }





    //在搜索栏通过用户电话号码搜索陌生人，可以找到对应的陌生人
    public Json_4_add_findpeople add_findpeople(Json_4_add_findpeople json_4_add_findpeople)
    {
        System.out.println("进入Logic-Link-add_findpeople");

        /**
         * 找到对应用户
         * 而且该用户还不是他原来的朋友
         */


        //找出来手机用户和待找用户
        System.out.println(json_4_add_findpeople.getPhoneNumber());
        System.out.println(json_4_add_findpeople.getFindPhoneNumber());
        UsertableEntity user=logicUtils.findUser(json_4_add_findpeople.getPhoneNumber());
        UsertableEntity toFindUser=logicUtils.findUser(json_4_add_findpeople.getFindPhoneNumber());

        //先判断有没有该用户
        if (toFindUser==null){
            System.out.println("手机号码错误，没有该用户");
            json_4_add_findpeople.setResult(SportClientSymbol.LinkPeople.AFP_RESULT_FAIL_OTHERNOTEXIST);
        }else {
            System.out.println("找到该用户");
            //有该用户，还要看是不是就是用户原来的朋友
            if (linkOperation.findOneLinkMan(user,toFindUser)==null){
                //原来这两个不是朋友
                json_4_add_findpeople.setFindIcon(toFindUser.getHeadIcon());
                json_4_add_findpeople.setFindNickname(toFindUser.getName());
                json_4_add_findpeople.setFindBrief(toFindUser.getBrief());
                json_4_add_findpeople.setResult(SportClientSymbol.LinkPeople.AFP_RESULT_SUCCESS);
            }else {
                System.out.println("这两个人以前就是朋友了！");
                json_4_add_findpeople.setResult(SportClientSymbol.LinkPeople.AFP_RESULT_FAIL_OTHERALREADY);
            }

        }


        return json_4_add_findpeople;
    }





    //在搜索栏通过群组名字找讨论群，可以找到几个同样名字的群
    public  ArrayList<Json_4_add_findgroup> add_findgroup(Json_4_add_findgroup json_4_add_findgroup)
    {
        System.out.println("进入Logic-Link-add_findgroup");

        ArrayList<Json_4_add_findgroup> resultList=new ArrayList<>();

        /**
         * 找到名字对应的群
         * 而且该群他还没有加进去
         */


        //找出来手机用户
        UsertableEntity user=logicUtils.findUser(json_4_add_findgroup.getPhoneNumber());
        //找出来待找群
        GrouptableEntity groupToSearch=new GrouptableEntity();
        groupToSearch.setTitle(json_4_add_findgroup.getGroupName());
        List<GrouptableEntity> toFindGroup =groupOperation.findByTitle(groupToSearch);
        //找出用户所在的所有群
        List<GrouptableEntity> userAllGroups=groLinkUserOperation.findOneUserAllGroup(user);

        //先判断有没有找到群组
        if (toFindGroup.size()==0){
            System.out.println("群组名字错误，找不到一个群组");
            json_4_add_findgroup.setResult(SportClientSymbol.LinkPeople.AFG_RESULT_FAIL_GROUPNOTEXIST);
            resultList.add(json_4_add_findgroup);
        }else {
            System.out.println("找到群组");
            System.out.println(toFindGroup.get(0).getTitle());
            //有该群组，还要看这个群组是不是已经在用户原来的群列表里，也就是用户已经加过了这个群了？
            for (int i = 0; i < toFindGroup.size(); i++) {
                //设置一个标志看这个群是不是在用户群列表里
                boolean flag=false;
                GrouptableEntity tempGroup=toFindGroup.get(i);
                for (int j = 0; j < userAllGroups.size(); j++) {
                    if (tempGroup.getId()==(userAllGroups.get(j).getId())){
                        //用户之前已经在这个群里了
                        flag=true;
                    }
                }
                if (!flag) {
                        //填充数据
                        json_4_add_findgroup.setGroupId(tempGroup.getId());
                        json_4_add_findgroup.setGroupIcon(tempGroup.getIcon());
                        json_4_add_findgroup.setGroupIntroduce(tempGroup.getTheam());
                        json_4_add_findgroup.setResult(SportClientSymbol.LinkPeople.AFG_RESULT_SUCCESS);
                        resultList.add(json_4_add_findgroup);
                    }
                }

                if (resultList.size()==0){
                    //说明有这个群组，但是用户已经在这个群组里面了
                    json_4_add_findgroup.setResult(SportClientSymbol.LinkPeople.AFG_RESULT_FAIL_GROUPALREADY);
                    resultList.add(json_4_add_findgroup);
                }

            }

        return resultList;
    }





    //在搜索栏通过电话找到人之后，点击添加，发送添加请求
    public Json_4_add_addpeople add_addpeople(Json_4_add_addpeople json_4_add_addpeople)
    {
        System.out.println("进入Logic-Link-add_addpeople");

        /**
         * 在申请表linkApplyHistory表添加一条记录
         */

        //先找到我和要申请的人的user实体
        UsertableEntity user=logicUtils.findUser(json_4_add_addpeople.getPhoneNumber());
        UsertableEntity toAddUser=logicUtils.findUser(json_4_add_addpeople.getAddPhoneNumber());

        //我以前申请过加他为好友了吗？
        if (linkAppHisOperation.findOneBy2User(user,toAddUser)==null){
            //以前没有申请过，需要在linkApplyHistory表新增一条记录
            System.out.println("以前没有申请过加他为好友");

            //新增请求记录，并且填充数据
            LinkapplyhistoryEntity newLinkApply=new LinkapplyhistoryEntity();
            newLinkApply.setStatus(SportServerSymbol.linkapplyhistory.STATUS_UNHANDLE);
            newLinkApply.setUsertableByApplyUserId(user);
            newLinkApply.setUsertableByBeApplyUserId(toAddUser);

            boolean shenqing=linkAppHisOperation.addOneApplyInfo(newLinkApply);
            if (shenqing){
                //发送请求成功
                System.out.println("发送请求成功");
                json_4_add_addpeople.setResult(SportClientSymbol.LinkPeople.AAP_RESULT_SUCCESS);

            }else {
                //发送请求失败
                System.out.println("发送请求失败-数据库操作时错误");
                json_4_add_addpeople.setResult(SportClientSymbol.LinkPeople.AAP_RESULT_FAIL_DATABASEWRONG);
            }
        }else {
            //以前有申请过，只需要在linkApplyHistory表修改该记录即可
            System.out.println("以前曾经申请过加他为好友");
            boolean shenqing=linkAppHisOperation.updateUserStatus(user,toAddUser,SportServerSymbol.linkapplyhistory.STATUS_UNHANDLE);
            if (shenqing){
                //发送请求成功
                System.out.println("发送请求成功");
                json_4_add_addpeople.setResult(SportClientSymbol.LinkPeople.AAP_RESULT_SUCCESS);

            }else {
                //发送请求失败
                System.out.println("发送请求失败-数据库操作时错误");
                json_4_add_addpeople.setResult(SportClientSymbol.LinkPeople.AAP_RESULT_FAIL_DATABASEWRONG);
            }
        }

        return json_4_add_addpeople;
    }






    //在搜索栏通过群组名字找到群后，点击添加，发送添加请求
    public Json_4_add_addgroup add_addgroup(Json_4_add_addgroup json_4_add_addgroup)
    {
        System.out.println("进入Logic-Link-add_addgroup");

        /**
         * 在申请表linkApplyHistory表添加一条记录
         */

        //先找到我的user实体和要申请的群的group实体
        UsertableEntity user=logicUtils.findUser(json_4_add_addgroup.getPhoneNumber());
        GrouptableEntity groupToSearch=new GrouptableEntity();
        groupToSearch.setId(json_4_add_addgroup.getAddGroupId());
        GrouptableEntity toAddGroup=groupOperation.findById(groupToSearch);

        //我以前申请过加入这个群了吗？
        if (linkAppHisOperation.findOneByUserAndGroup(user,toAddGroup)==null){
            //以前没有申请过，需要在linkApplyHistory表新增一条记录
            System.out.println("以前没有申请过加入这个群");

            //新增请求记录，并且填充数据
            LinkapplyhistoryEntity newLinkApply=new LinkapplyhistoryEntity();
            newLinkApply.setStatus(SportServerSymbol.linkapplyhistory.STATUS_UNHANDLE);
            newLinkApply.setUsertableByApplyUserId(user);
            newLinkApply.setGrouptableByBeApplyGroupId(toAddGroup);

            boolean shenqing=linkAppHisOperation.addOneApplyInfo(newLinkApply);
            if (shenqing){
                //发送请求成功
                System.out.println("发送请求成功");
                json_4_add_addgroup.setResult(SportClientSymbol.LinkPeople.AAG_RESULT_SUCCESS);

            }else {
                //发送请求失败
                System.out.println("发送请求失败-数据库操作时错误");
                json_4_add_addgroup.setResult(SportClientSymbol.LinkPeople.AAG_RESULT_FAIL_DATABASEWRONG);
            }
        }else {
            //以前有申请过，只需要在linkApplyHistory表修改该记录即可
            System.out.println("以前曾经申请过加入这个群");
            boolean shenqing=linkAppHisOperation.updateGroupStatus(user,toAddGroup,SportServerSymbol.linkapplyhistory.STATUS_UNHANDLE);
            if (shenqing){
                //发送请求成功
                System.out.println("发送请求成功");
                json_4_add_addgroup.setResult(SportClientSymbol.LinkPeople.AAG_RESULT_SUCCESS);

            }else {
                //发送请求失败
                System.out.println("发送请求失败-数据库操作时错误");
                json_4_add_addgroup.setResult(SportClientSymbol.LinkPeople.AAG_RESULT_FAIL_DATABASEWRONG);
            }
        }

        return json_4_add_addgroup;
    }

}
